package com.gcit.seniorWish.web.modular.examinee.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.persistence.model.SeniorSchoolClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.base.tips.Tip;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.core.node.SelectNode;
import com.gcit.seniorWish.core.util.ToolUtil;
import com.gcit.seniorWish.web.common.constant.Const;
import com.gcit.seniorWish.web.common.constant.enums.ManagerStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.RoleEnum;
import com.gcit.seniorWish.web.common.constant.enums.UserTypeEnum;
import com.gcit.seniorWish.web.common.constant.factory.PageFactory;
import com.gcit.seniorWish.web.common.persistence.dao.SeniorSchoolMapper;
import com.gcit.seniorWish.web.common.persistence.model.Role;
import com.gcit.seniorWish.web.common.persistence.model.SeniorSchool;
import com.gcit.seniorWish.web.common.persistence.model.User;
import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolClassService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolService;
import com.gcit.seniorWish.web.modular.system.service.IRoleService;
import com.gcit.seniorWish.web.modular.system.service.IUserMgrService;

import cn.hutool.core.util.StrUtil;

/**
 * 学校信息
 *
 * @author tonglu
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/seniorschool")
public class SeniorSchoolController extends BaseController {

	private static String PREFIX = "/examinee/school";

	@Resource
	private SeniorSchoolMapper seniorSchoolMapper;

	@Autowired
	ISeniorSchoolService seniorSchoolService;

	@Autowired
	private ISeniorSchoolClassService seniorSchoolClassService;

	@Autowired
	private IUserMgrService userMgrService;

	@Autowired
	IRoleService roleService;

	/**
	 * 数据列表
	 */
	@RequestMapping("")
	public String school() {
		return PREFIX + "/school.html";
	}

	/**
	 * 获取学校列表
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(@RequestParam(required = false) String schoolName,
	                   @RequestParam(required = false) String schoolCode) {
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		EntityWrapper<SeniorSchool> ew = new EntityWrapper<SeniorSchool>();
		if (StrUtil.isNotBlank(schoolCode))
			ew.like("school_code", schoolCode);
		if (StrUtil.isNotBlank(schoolName))
			ew.like("school_name", schoolName);
		/*
		 * if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType())
		 * {// 登录人为班主任 ew.eq("school_id", ShiroKit.getUser().getSchoolId());
		 * ew.eq("class_id", ShiroKit.getUser().getClassId()); } else if
		 * (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {//
		 * 登录人为学校管理员 ew.eq("school_id", ShiroKit.getUser().getSchoolId()); }
		 */
		page = seniorSchoolService.selectMapsPage(page, ew);
		return packForBT(page);
	}

	/**
	 * 跳转到编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(SeniorSchool seniorSchool, Model model) {
		seniorSchool = seniorSchoolMapper.selectById(seniorSchool.getId());
		if (seniorSchool == null)
			seniorSchool = new SeniorSchool();
		model.addAttribute("seniorSchool", seniorSchool);
		return PREFIX + "/schoolEdit.html";
	}

	/**
	 * 学校保存
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/save")
	@ResponseBody
	public Tip save(SeniorSchool seniorSchool) {
		//判断该班级代号是否存在
		EntityWrapper<SeniorSchool> ew = new EntityWrapper<>();
		ew.eq("school_code", seniorSchool.getSchoolCode());
		//当id存在时，判断需要排除该记录
		if (StrUtil.isNotBlank(seniorSchool.getId())) {
			ew.ne("id", seniorSchool.getId());
		}
		if (this.seniorSchoolService.selectCount(ew) > 0) {// 该班级代号已存在
			throw new GunsException(BizExceptionEnum.SENIOR_SCHOOL_CODE_EXIST);
		}

		//id存在时，数据库存在
		if (StrUtil.isNotBlank(seniorSchool.getId())) {
			//查询已经存在的学校信息，用于查询用户表中已经存在的用户（防止编号修改找不到用户）
			SeniorSchool existSchool = ConstantFactory.me().getSeniorSchoolById(seniorSchool.getId());
			//编号不同时，需要查询修改后的形成的用户名在用户表中是否存在
			if (!seniorSchool.getSchoolCode().equals(existSchool.getSchoolCode())) {
				//新增数据时，查询班级对应的班级管理员所用账号在用户表中是否存在
				if (userMgrService.selectCount(Condition.create().eq("account", "szwz" + seniorSchool.getSchoolCode())) > 0) {// 用户名已存在
					throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
				}
			}
		} else {
			//新增数据时，查询班级对应的班级管理员所用账号在用户表中是否存在
			if (userMgrService.selectCount(Condition.create().eq("account", "szwz" + seniorSchool.getSchoolCode())) > 0) {// 用户名已存在
				throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
			}
		}
		seniorSchoolService.mergeSeniorSchool(seniorSchool);


		return SUCCESS_TIP;
	}

	/**
	 * 删除学校
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/remove")
	@ResponseBody
	public Tip remove(@RequestParam String schoolId) {
		if (ToolUtil.isEmpty(schoolId)) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		if (seniorSchoolClassService.selectCount(Condition.create().eq("senoir_school_id", schoolId)) > 0) {
			throw new GunsException(BizExceptionEnum.SCHOOL_HAVE_CLASS);
		}
		// 删除对应的用户
		SeniorSchool school = seniorSchoolMapper.selectById(schoolId);
		this.seniorSchoolMapper.deleteById(schoolId);
		User user = userMgrService.selectOne(Condition.create().eq("account", "szwz" + school.getSchoolCode()));
		if (user != null) {
			userMgrService.deleteUser(user.getId());
		}
		return SUCCESS_TIP;
	}

	/**
	 * 查询学校列表 term 模糊查询
	 *
	 * @author tonglu
	 * @date 2018-03-19 下午 4:01
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	@RequestMapping(value = "/listSchoolForSelect2")
	@ResponseBody
	public Object listSchoolForSelect2(String term) {
		Page<SelectNode> page = new Page();
		if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()
				|| UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 表示
			page.setRecords(seniorSchoolService.listSchoolForSelect2(term, ShiroKit.getUser().getSchoolId()));
		} else {
			page.setRecords(seniorSchoolService.listSchoolForSelect2(term, null));
		}
		return packForSelect2(page);
	}
}
